﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cat.Domain.Entities;
using System.Web;
using Cat.Domain.Repositories.Resume;
using Cat.Domain.Entities.Resume;
using Cat.Domain.Services.Authentication;

namespace Cat.Web.Framework
{
    public partial class WorkContext : IWorkContext
    {
        private const string PassportCookieName = "Dice.passport";

        private readonly HttpContextBase _httpContext;
        private readonly IJobseekerRepository _passportRepository;
        private readonly IAuthenticationService _authenticationService;

        private Jobseeker _cachedPassport;

        public WorkContext(HttpContextBase httpContext,
             IJobseekerRepository passportRepository,
              IAuthenticationService authenticationService)
        {

            this._httpContext = httpContext;
            this._passportRepository = passportRepository;
            this._authenticationService = authenticationService;
        }

        protected Jobseeker GetCurrentPassport()
        {
            if (_cachedPassport != null)
                return _cachedPassport;

            Jobseeker passport = null;
            if (_httpContext != null)
            {

                // 处理搜索引擎的登录
                //if (IsSerchEngine) { }

                if (passport == null)
                {
                    passport = _authenticationService.GetAuthenticatedJobseeker();
                }

                SetPassportCookie(passport.JobSeekerID);
            }

            // Validation
            if (passport != null)
            {
                // 更新上次活动日期

                // 更新IP地址

                _cachedPassport = passport;
            }

            return _cachedPassport;
        }

        protected HttpCookie GetCustomerCookie()
        {
            if (_httpContext == null || _httpContext.Request == null)
                return null;

            return _httpContext.Request.Cookies[PassportCookieName];
        }

        protected void SetPassportCookie(Guid passportGuid)
        {
            var cookie = new HttpCookie(PassportCookieName);
            cookie.Value = passportGuid.ToString();

            if (passportGuid == Guid.Empty)
            {
                cookie.Expires = DateTime.Now.AddMonths(-1);
            }
            else
            {
                int cookieExpires = 24 * 365; //TODO make configurable
                cookie.Expires = DateTime.Now.AddHours(cookieExpires);
            }
        }

        public Jobseeker CurrentJobseeker
        {
            get
            {
                return GetCurrentPassport();
            }
            set
            {
                SetPassportCookie(value.JobSeekerID);
                _cachedPassport = value;
            }
        }




    }
}
